package com.onlyxiahui.extend.query.hibernate.syntax.util;

import java.util.List;

import com.onlyxiahui.extend.query.hibernate.QueryWrapper;
import com.onlyxiahui.extend.query.hibernate.syntax.data.BracketInfo;
import com.onlyxiahui.extend.query.hibernate.syntax.data.OrderByInfo;
import com.onlyxiahui.extend.query.hibernate.syntax.data.QueryColumn;
import com.onlyxiahui.extend.query.hibernate.syntax.data.QueryHandleData;
import com.onlyxiahui.extend.query.hibernate.util.DbStringUtil;

/**
 * 
 * Description <br>
 * Date 2020-02-01 11:32:44<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
public class QueryHqlUtil {

	public static String getQueryHql(String entityName, QueryWrapper qw) {
		return getQueryHql(entityName, qw, null, false);
	}

	public static String getQueryHql(String entityName, QueryWrapper qw, boolean isCount) {
		return getQueryHql(entityName, qw, null, isCount);
	}

	public static String getQueryHql(String entityName, QueryWrapper qw, QueryHandleData queryHandleData) {
		return getQueryHql(entityName, qw, queryHandleData, false);
	}

	public static String getQueryHql(String entityName, QueryWrapper qw, QueryHandleData queryHandleData, boolean isCount) {

		List<OrderByInfo> orderByInfos = (null != queryHandleData) ? queryHandleData.getOrderByInfos() : null;
		List<QueryColumn> columns = (null != queryHandleData) ? queryHandleData.getColumns() : null;
		List<BracketInfo> brackets = (null != queryHandleData) ? queryHandleData.getBrackets() : null;

		String alias = "data";

		String where = BaseHqlUtil.getWhereHqlByColumns(alias, qw, columns, brackets);
		String orderBy = BaseHqlUtil.getOrderByHql(alias, orderByInfos);

		StringBuilder hql = new StringBuilder();

		hql.append("select");
		hql.append(" ");
		if (isCount) {
			hql.append("count(*)");
		} else {
			hql.append(alias);
		}

		hql.append(" ");
		hql.append("from");
		hql.append(" ");
		hql.append(entityName);

		hql.append(" ");
		hql.append(alias);

		if (DbStringUtil.isNotBlank(where)) {
			hql.append(" ");
			hql.append(where);
		}
		if (DbStringUtil.isNotBlank(orderBy) && !isCount) {
			hql.append(" ");
			hql.append(orderBy);
		}
		return hql.toString();
	}
}
